package com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.ViewModelProvider;

import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.R;
import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.activity.doctor.ActivityHomeDoctor;
import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.activity.parent.ActivityHomeParent;
import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.databinding.ActivityRegisterBinding;
import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.model.UserViewModel;
import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.utils.GlobalViewModelStore;
import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.utils.MyApplication;
import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.viewmodel.RegisterViewModel;

//注册界面
public class ActivityRegister extends AppCompatActivity {

    private ActivityRegisterBinding binding;
    private RegisterViewModel viewModel;
    private String[] roles = {"parent", "doctor"};  //身份选择下拉框选项
    private int curRole = 0;    //当前选择的角色的序号
    private UserViewModel userViewModel;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivityRegisterBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        /*：为 Android 应用中 R.id.register 对应的视图设置窗口插入监听器，
        依据系统栏（如状态栏、导航栏）的位置和大小动态调整该视图内边距，防止视图被系统栏遮挡。*/
        ViewCompat.setOnApplyWindowInsetsListener(binding.getRoot(), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        viewModel = new ViewModelProvider(this).get(RegisterViewModel.class);
        viewModel.initViews(this);

        setUserViewModel();

        setSpinner();

        //发送验证码
        viewModel.btnSendTelCode.getValue().setOnClickListener(v -> {
            // 这里可以添加发送验证码的逻辑
            // 例如，调用 API 发送验证码到用户的手机
            // 然后更新 UI，显示倒计时
            viewModel.startCountdown(this);
        });

        // 修改：调用异步验证方法
        viewModel.btnFinishAndRegister.getValue().setOnClickListener(v -> {
            viewModel.validateRegistrationAsync(this, isValid -> {
                if (isValid) {
                    var targetActivity = curRole==0?ActivityHomeParent.class:ActivityHomeDoctor.class;
                    userViewModel.setUserType(roles[curRole]);
                    Intent intent = new Intent(ActivityRegister.this, targetActivity);
                    startActivity(intent);
                    Toast.makeText(ActivityRegister.this, "注册成功！", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(ActivityRegister.this, viewModel.getErrorMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        });

        //返回登录界面
        viewModel.tevReturnLogin.getValue().setOnClickListener(v -> {
            Intent intent = new Intent(ActivityRegister.this, ActivityLogin.class);
            startActivity(intent);
        });

    }

    private void setSpinner(){
        // 创建适配器，使用 strings.xml 中的数组资源
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this,
                R.array.roleArray,
                android.R.layout.simple_spinner_dropdown_item
        );
        // 设置下拉列表的样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // 将适配器设置给 Spinner
        viewModel.spinnerRoleSelect.getValue().setAdapter(adapter);

        // 为 Spinner 添加选择监听器
        viewModel.spinnerRoleSelect.getValue().setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(android.widget.AdapterView<?> parent, android.view.View view, int position, long id) {
                // 获取选中的值
                String selectedValue = parent.getItemAtPosition(position).toString();
                if (selectedValue.equals("医生")) {
                    curRole = 1;
                } else if (selectedValue.equals("家长")) {
                    curRole = 0;
                }
            }

            @Override
            public void onNothingSelected(android.widget.AdapterView<?> parent) {
                // 当没有选择任何项时的处理
            }
        });
    }

    private void setUserViewModel(){
        //用户身份
        // 获取全局共享的 UserViewModel
        userViewModel = GlobalViewModelStore
                .getInstance(MyApplication.getInstance())
                .get(UserViewModel.class);
    }
}